const PENDING = 'PENDING'
const FULLFILLED = 'FULLFILLED'
const REJECTED = 'REJECTED'


// 解决resolve异步执行问题
// 1. 将then传递的回调函数暂存在数组this.onFullfilledArr中，
// 2. 执行resolve时再遍历该数组执行回调函数
class Promise {
    constructor(excute){
        this.state = PENDING
        this.value = ''
        this.error = ''
        this.onFullfilledArr = []
        this.onRejectedArr = []

        const resolve  = (value) => {
            console.log(value)
            if(this.state === PENDING){
                this.state = FULLFILLED
                this.value = value
                this.onFullfilledArr.forEach((fn)=>{
                    fn(value)
                })
            }
        }

        const reject = (error) => {
            console.log(error)
            if(this.state === PENDING){
                this.state = REJECTED
                this.error = error
            }
        }

        try {
            excute(resolve, reject)
        } catch (e) {
            reject(e)
        }
    }

    then(onFullfilled){
        this.onFullfilledArr.push(()=>{
            onFullfilled()
        })
        
    }

    catch(onRejected){
       this.onRejectedArr.push(()=>{
            onRejected()
       })
    }
}

new Promise((resolve, reject) => {
    setTimeout(()=>{
        resolve(123)
    }, 1000)
}).then(()=>{
    console.log(1111)
})